package com.edu.policy.data.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class DataClient {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline().addLast(new SimpleClientHandler());
                        }
                    });

            // 连接服务器
            ChannelFuture f = b.connect("101.201.63.50", 12580).sync();

            // 测试数据
            byte[] receivedData = new byte[] {
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x25,  // 协议头部（6字节）
                    0x01, 0x01,                         // 设备地址和功能码
                    0x6E, 0x68, 0x61, 0x6E, 0x6A, 0x69, 0x68, 0x6E, 0x68, 0x68, 0x75, 0x61, 0x6E, 0x62, 0x61, 0x6F, 0x67, 0x6F, 0x6E, 0x67, 0x73, 0x69, 0x31, 0x68, 0x61, 0x6F, 0x63, 0x68, 0x75, 0x63, 0x68, 0x65, 0x6E, 0x71, 0x69 // ASCII码转换后的数据部分
            };
            ByteBuf byteBuf = Unpooled.copiedBuffer(receivedData);
            f.channel().writeAndFlush(byteBuf).sync();  // 发送数据并同步等待发送完成

            System.out.println("发送完成");

            // 发送完数据后关闭连接
            f.channel().close().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    static class SimpleClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println(cause.getLocalizedMessage());
            ctx.close();
        }
    }
}


